<template>
  <h1>二维码生成与下载</h1>
  <input v-model="text" placeholder="输入内容" />
  <br />
  <!-- <input v-model="description" placeholder="输入描述" /> -->
  <button @click="generateQRCode">生成二维码</button>
  <br />
  <canvas ref="qrcodeCanvas"></canvas>
  <br />
  <a :href="downloadLink" download="qrcode.png">下载二维码</a>
</template>
  
<script lang='ts' setup>
import QRCode from "qrcode";

const text = ref<any>("");
const downloadLink = ref<any>("");
const qrcodeCanvas = ref<any>(null);
const description = ref("");

const generateQRCode = () => {
  if (qrcodeCanvas.value) {
    QRCode.toCanvas(qrcodeCanvas.value, text.value, (error: any) => {
      if (error) {
        console.error(error);
        return;
      }
      console.log("成功生成二维码");
      downloadLink.value = qrcodeCanvas.value.toDataURL("image/png");
    });
  }
};

// const generateQRCode = () => {
//   if (qrcodeCanvas.value) {
//     const canvas = qrcodeCanvas.value;
//     const ctx = canvas.getContext('2d');

//     // 清空 canvas
//     ctx.clearRect(0, 0, canvas.width, canvas.height);

//     QRCode.toCanvas(canvas, text.value, { margin: 1 }, (error) => {
//       if (error) {
//         console.error(error);
//         return;
//       }
//       console.log('成功生成二维码');

//       // 在二维码下方添加文字描述
//       const qrCodeHeight = canvas.height;
//       ctx.font = '16px Arial';
//       ctx.textAlign = 'center';
//       ctx.fillText(description.value, canvas.width / 2, qrCodeHeight + 20);

//       // 更新下载链接
//       downloadLink.value = canvas.toDataURL('image/png');
//     });
//   }
// };
</script>
  
<style scoped lang='less'>
</style>
